<template>
  <div>
    <el-card style="margin-bottom: 20px">
      <el-form inline class="form">
        <el-form-item label="角色名称：">
          <el-input placeholder="请输入角色名称" v-model="roleName"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="query()" :disabled="!roleName">
            查询
          </el-button>
          <el-button type="primary" @click="resetQuery()">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <el-button type="primary" @click="openDrawer">添加角色</el-button>
      <el-table style="margin: 10px 0" border :data="roleList">
        <el-table-column type="selection"></el-table-column>
        <el-table-column label="#" width="40" type="index"></el-table-column>
        <el-table-column label="角色id" prop="id"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="remark"></el-table-column>
        <el-table-column label="创建时间" prop="createTime"></el-table-column>
        <el-table-column label="更新时间" prop="updateTime"></el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              icon="user"
              size="small"
              @click="openRoleDrawer(row)"
            >
              分配权限
            </el-button>
            <el-button
              type="primary"
              icon="edit"
              title="编辑"
              size="small"
              @click="edit(row)"
            ></el-button>
            <el-popconfirm
              :title="`确定删除${row.roleName}吗？`"
              width="210"
              @confirm="deleteRole(row.id)"
              confirm-button-text="确定"
              cancel-button-text="取消"
            >
              <template #reference>
                <el-button
                  type="danger"
                  size="small"
                  icon="delete"
                  title="删除"
                ></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[3, 6, 9, 12]"
        :size="size"
        :disabled="disabled"
        :background="background"
        layout=" prev, pager, next, jumper, ->,sizes, total"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <el-drawer v-model="drawerFlag">
        <template #header>
          <h4>
            {{ roleData.id ? '编辑角色' : '添加角色' }}
          </h4>
        </template>
        <template #default>
          <div>
            <el-form
              ref="roleFormRef"
              label-position="right"
              label-width="100"
              :model="roleData"
              :rules="rules"
            >
              <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="roleData.roleName"></el-input>
              </el-form-item>
              <el-form-item label="角色描述" prop="remark">
                <el-input v-model="roleData.remark"></el-input>
              </el-form-item>
            </el-form>
          </div>
        </template>
        <template #footer>
          <div style="flex: auto">
            <el-button @click="cancelClick">取消</el-button>
            <el-button type="primary" @click="confirmClick">保存</el-button>
          </div>
        </template>
      </el-drawer>

      <el-drawer v-model="roleDrawerFlag">
        <template #header>
          <h4>分配权限</h4>
        </template>
        <template #default>
          <el-tree
            ref="treeRef"
            style="max-width: 600px"
            :data="permissionData"
            show-checkbox
            node-key="id"
            default-expand-all
            :default-checked-keys="selectedMenuList"
            :props="defaultProps"
          />
        </template>
        <template #footer>
          <div style="flex: auto">
            <el-button @click="permissionCancelClick">取消</el-button>
            <el-button type="primary" @click="permissionConfirmClick">
              保存
            </el-button>
          </div>
        </template>
      </el-drawer>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="index">
import { onMounted, ref, nextTick } from 'vue'
import {
  reqRoleList,
  reqDeleteRole,
  reqAddRole,
  reqUpdateRole,
  reqGetMenu,
  reqSaveRole,
} from '@/api/acl/role'
import type { RoleData, PermissionData } from '@/api/acl/role/type'
import { ElMessage } from 'element-plus'
import useLayoutStore from '@/store/modules/setting.ts'
const layoutStore = useLayoutStore()
const currentPage = ref(1)
const pageSize = ref(3)
const total = ref(0)
const size = ref('small')
const disabled = ref(false)
const background = ref(true)

const roleName = ref('')
const query = () => {
  getRoleList()
}
const resetQuery = () => {
  layoutStore.refresh = !layoutStore.refresh
}
const roleList = ref<RoleData[]>([])

//
const drawerFlag = ref(false)

const roleData = ref<RoleData>({
  roleName: '',
  remark: '',
  id: '',
})
const handleSizeChange = (val: number) => {
  console.log(`每页 ${val} 条`)
  getRoleList(val)
}
const handleCurrentChange = (val: number) => {
  console.log(`当前页: ${val}`)
  getRoleList(val)
}
const getRoleList = async (page: number = 1) => {
  currentPage.value = page
  let res = await reqRoleList(currentPage.value, pageSize.value, roleName.value)
  if (res.code === 200) {
    console.log('获取用户列表成功', res.data)
    roleList.value = res.data.records
    total.value = res.data.total
  }
}
onMounted(() => {
  getRoleList()
})
const openDrawer = () => {
  console.log('add')
  roleData.value = {
    roleName: '',
    remark: '',
    id: '',
  }
  drawerFlag.value = true
  roleFormRef.value?.clearValidate()
}
//编辑
const edit = (row: RoleData) => {
  console.log('edit', row)
  roleData.value = row
  drawerFlag.value = true
  nextTick(() => {
    //清除表单的校验信息
    roleFormRef.value.clearValidate()
  })
}
//取消
const cancelClick = () => {
  drawerFlag.value = false
}

const rules = ref({
  roleName: [{ required: true, message: '请输入角色名', trigger: 'blur' }],
})
const roleFormRef = ref<any>()
//保存
const confirmClick = async () => {
  // 验证表单
  await roleFormRef.value.validate()
  if (roleData.value.id) {
    let res = await reqUpdateRole(roleData.value)
    console.log('更新角色成功', res)
    if (res.code === 200) {
      ElMessage.success('更新角色成功')
    } else {
      ElMessage.error('更新角色失败')
    }
    drawerFlag.value = false
  } else {
    let res = await reqAddRole(roleData.value)
    console.log('添加角色成功', res)
    if (res.code === 200) {
      ElMessage.success('添加角色成功')
    } else {
      ElMessage.error('添加角色失败')
    }
    drawerFlag.value = false
    getRoleList()
  }
}
//删除
const deleteRole = async (id: number) => {
  console.log('delete', id)
  let res = await reqDeleteRole(id)
  if (res.code === 200) {
    ElMessage.success('删除角色成功')
    getRoleList()
  } else {
    ElMessage.error('删除角色失败')
  }
}
//权限分配
const defaultProps = {
  children: 'children',
  label: 'name',
}
const roleDrawerFlag = ref(false)
const treeRef = ref()
const permissionData = ref<PermissionData[]>([])
//选中的权限
const selectedMenuList = ref<number[]>([])
const openRoleDrawer = async (row: RoleData) => {
  console.log('分配角色', row)
  roleDrawerFlag.value = true
  selectedMenuList.value = []
  roleData.value = row
  //根据角色获取菜单权限
  let res = await reqGetMenu(row.id as number)
  if (res.code === 200) {
    console.log('根据角色获取菜单权限成功', res)
    permissionData.value = res.data
    //获取选中的权限
    // selectedMenuList.value = getSelectedMenu(permissionData.value)
    //过滤第4级的id  递归过滤
    selectedMenuList.value = filterMenu4(permissionData.value)
    console.log('选择==》', selectedMenuList)
  }
}
const filterMenu4 = (data: PermissionData[]) => {
  let arr: number[] = []
  data.forEach((item) => {
    if (item.children) {
      arr = arr.concat(filterMenu4(item.children))
    }
    if (item.level === 4 && item.select) {
      arr.push(item.id)
    }
  })
  return arr
}
//获取选中的权限
const getSelectedMenu = (data: PermissionData[]) => {
  let arr: number[] = []
  data.forEach((item) => {
    if (item.children) {
      arr = arr.concat(getSelectedMenu(item.children))
    }
    console.log('id:select:name', item.id, item.select, item.name)
    if (item.select) {
      arr.push(item.id as number)
    }
  })
  return arr
}
const permissionCancelClick = () => {
  roleDrawerFlag.value = false
}
const permissionConfirmClick = async () => {
  console.log('保存权限---->')
  let res = await reqSaveRole(
    roleData.value.id as number,
    treeRef.value.getCheckedKeys(),
  )
  if (res.code === 200) {
    ElMessage.success('保存权限成功')
    roleDrawerFlag.value = false
    //页面刷新
    window.location.reload()
  } else {
    ElMessage.error('保存权限失败')
  }
}
</script>

<style scoped lang="scss">
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
